

import rpyc
import cPickle, pickle
from dexen.system.libs import _constants 

__script_api = None
__settings_api = None

def _createScriptApi(url, schema_name, pop_name, script_name):
    global __script_api
    __script_api = ScriptAPI(url, schema_name, pop_name, script_name)

def _createSettingsApi(url, schema_name, pop_name):
    global __settings_api
    __settings_api = SettingsAPI(url, schema_name, pop_name)

def getScriptApi():
    return __script_api

def getSettingsApi():
    return __settings_api
  
class SettingsAPI:       
    def __init__(self, url, schema_name, pop_name):
        self.schema_name = schema_name
        self.pop_name = pop_name
        self.conn = rpyc.connect(url, port = _constants._SETTINGS_API_PORT)
        self.conn.root.setRPYCObj(schema_name, pop_name)
    
    def setDataStructure(self, attributes):
        self.conn.root.setDataStructure(cPickle.dumps(attributes))

    def setObjectives(self, attributes):
        self.conn.root.setObjectives(cPickle.dumps(attributes))
    
    def setImage(self, image_name):
        self.conn.root.setImage(image_name)
    
    def setModel(self, model_name):
        self.conn.root.setModel(model_name)
    
    def setMaxIndividuals(self, max_individuals):
        self.conn.root.setMaxIndividuals(max_individuals)
    
    def setScript(self, script_name, file_name, function_name):        
        self.conn.root.setScript(script_name, file_name, function_name)

class ScriptAPI:
    def __init__(self, url, schema_name, pop_name, script_name):
        self.url = url
        self.schema_name = schema_name
        self.pop_name = pop_name
        self.script_name = script_name
        self.conn = rpyc.connect(url, _constants._SCRIPT_API_PORT)
        self.conn.root.setRPYCObj(schema_name, pop_name, script_name)
        
    def downloadIndividuals(self, select, where=None, count=None, order_by=None, exclusive_use=True):
        individuals = self.conn.root.getIndividuals(select, where, count, order_by, exclusive_use)
        return cPickle.loads(individuals)
    
    def uploadIndividuals(self, individuals):
        self.conn.root.setIndividuals(cPickle.dumps(individuals, pickle.HIGHEST_PROTOCOL))